package cn.com.cis.utils.jobExecute;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.com.cis.domain.JobLog;
import cn.com.cis.service.JobLogService;
import scriptella.interactive.ProgressIndicator;

/**
 * Progress indicator to send out
 *
 * @author lwang
 * @version 1.0
 */
public class CisJobProgressIndicator implements ProgressIndicator {

    private int logId = -1;

    private String jobName;

    private String username;

    private JobLogService js;
    
    private String executorThread;

    @Override
    public void showProgress(double progress, String message) {

        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowString = df.format(now);
        String logMessage = "(" + nowString + ") - " + message + ": " + progress * 100 + "%";

        if (-1 == logId) {
            JobLog log = new JobLog();
            log.setBeginTime(now);
            log.setLogDate(now);
            log.setStatus(progress + ""); // save the progress
            log.setJobName(jobName);
            log.setMessage(logMessage);
            log.setUsername(username);
            log.setExecutorThread(executorThread);
            js.insertJobEntityLog(log);

            logId = log.getId();
        } else {
            JobLog log = js.selectJobEntityLogById(logId);

            String oldMessage = log.getMessage();
            log.setMessage(oldMessage + "\n" + logMessage);

            log.setLogDate(now);
            log.setStatus(progress + "");
            if(1.0 == progress){
                log.setEndTime(now);
                log.setStatus("success");
            }

            js.updateJobEntityLog(log);
        }
    }

    public void onError(String message) {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowString = df.format(now);

        JobLog log = js.selectJobEntityLogById(logId);

        log.setStatus("failed");
        log.setEndTime(now);
        log.setLogDate(now);
        log.setMessage(log.getMessage() + "\n(" + nowString + ") - " + message);

        js.updateJobEntityLog(log);
    }

    public void setLogId(int logId) {
        this.logId = logId;
    }

    public int getLogId() {
        return logId;
    }

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    public String getJobName() {
        return jobName;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserName() {
        return username;
    }

    public void setJs(JobLogService js) {
        this.js = js;
    }

	public String getExecutorThread() {
		return executorThread;
	}

	public void setExecutorThread(String executorThread) {
		this.executorThread = executorThread;
	}
}
